package com.joinway.framework.admin.core.service.table;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.joinway.framework.core.plugin.PluginManager;
import com.joinway.framework.core.utils.FrameworkHelper;

@Service
public class TableServiceFactory {

//	private static ApplicationContext ctx;
	
//	@Autowired protected ITableServiceRepository repository;
	
	public static ITableService getInstance(String tableName){
//		TableServiceFactory factory = ctx.getBean(TableServiceFactory.class);
		
		ITableService target = null;
//		ctx.getBean("adminRoleTableService");
//		List<ITableService> list = Arrays.asList(factory.repository.getServices().stream().filter(t -> t.getTableName().equals(tableName)).toArray(ITableService[]::new));
		
		ITableServiceRepository repository = FrameworkHelper.getBean(ITableServiceRepository.class);
		List<ITableService> services = repository.getServices();
		
		List<ITableService> targets = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(services)){
			for(ITableService service : services){
				if(service.getTableName().equals(tableName)){
					targets.add(service);
				}
			}
		}
		
		if(CollectionUtils.isNotEmpty(targets)){
			target = PluginManager.getInstance(targets);
		}
		
		if(target == null){
			target = repository.getDefaultService();
		}
		
		return target;
	}

//	@Override
//	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
//		TableServiceFactory.ctx = ctx;
//	}
}
